//
//  SocialMediaRulesView.swift
//  CMB250716
//
//  Created by Trae AI on 2025/01/15.
//

import SwiftUI

struct SocialMediaRulesView: View {
    @Environment(\.presentationMode) var presentationMode
    @EnvironmentObject var dataManager: DataManager
    @EnvironmentObject var socialMediaManager: SocialMediaManager
    
    let userId: String
    let onConfirm: () -> Void
    
    @State private var hasScrolledToBottom = false
    @State private var showConfirmButton = false
    @State private var animateContent = false
    @State private var animateBackground = false
    
    private var language: String {
        return dataManager.currentLanguage
    }
    
    var body: some View {
        ZStack {
            // 优化的背景渐变
            LinearGradient(
                colors: [
                    Color.black.opacity(0.85),
                    Color.black.opacity(0.75),
                    Color.black.opacity(0.65)
                ],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .ignoresSafeArea()
            .scaleEffect(animateBackground ? 1.0 : 1.1)
            .opacity(animateBackground ? 1.0 : 0.0)
            .animation(.easeOut(duration: 0.4), value: animateBackground)
            .onTapGesture {
                dismissWithAnimation()
            }
            
            // 主要内容卡片
            VStack(spacing: 0) {
                // 优化的顶部标题栏
                HStack {
                    HStack(spacing: 8) {
                        Image(systemName: "doc.text.fill")
                            .font(.system(size: 18, weight: .semibold))
                            .foregroundStyle(
                                LinearGradient(
                                    colors: [Color(red: 0.0, green: 0.8, blue: 1.0), Color(red: 0.4, green: 0.6, blue: 1.0)],
                                    startPoint: .leading,
                                    endPoint: .trailing
                                )
                            )
                        
                        Text(language == "zh" ? "社交媒体积分规则" : "Social Media Points Rules")
                            .font(.system(size: 18, weight: .bold, design: .rounded))
                            .foregroundStyle(
                                LinearGradient(
                                    colors: [Color(red: 0.0, green: 0.8, blue: 1.0), Color(red: 0.4, green: 0.6, blue: 1.0)],
                                    startPoint: .leading,
                                    endPoint: .trailing
                                )
                            )
                    }
                    
                    Spacer()
                    
                    Button(action: {
                        dismissWithAnimation()
                    }) {
                        Image(systemName: "xmark.circle.fill")
                            .font(.system(size: 22))
                            .foregroundColor(.white.opacity(0.8))
                            .background(
                                Circle()
                                    .fill(Color.black.opacity(0.2))
                                    .frame(width: 30, height: 30)
                            )
                    }
                    .scaleEffect(1.0)
                    .animation(.spring(response: 0.3, dampingFraction: 0.7), value: animateContent)
                }
                .padding(.horizontal, 20)
                .padding(.top, 16)
                .padding(.bottom, 12)
                
                // 优化的滚动内容
                ScrollViewReader { proxy in
                    ScrollView(.vertical, showsIndicators: false) {
                        LazyVStack(alignment: .leading, spacing: 16) {
                            rulesContent
                        }
                        .padding(.horizontal, 18)
                        .padding(.bottom, showConfirmButton ? 120 : 80)
                        .background(
                            GeometryReader { geometry in
                                Color.clear
                                    .onAppear {
                                        checkScrollPosition(geometry: geometry)
                                    }
                                    .onChange(of: geometry.frame(in: .global).minY) { _ in
                                        checkScrollPosition(geometry: geometry)
                                    }
                            }
                        )
                    }
                    .opacity(animateContent ? 1.0 : 0.0)
                    .offset(y: animateContent ? 0 : 20)
                    .animation(.easeOut(duration: 0.5).delay(0.2), value: animateContent)
                }
                
                // 优化的底部确认按钮
                if showConfirmButton {
                    VStack(spacing: 0) {
                        // 渐变分隔线
                        LinearGradient(
                            colors: [
                                Color.clear,
                                Color.white.opacity(0.3),
                                Color.clear
                            ],
                            startPoint: .leading,
                            endPoint: .trailing
                        )
                        .frame(height: 1)
                        .padding(.horizontal, 20)
                        
                        Button(action: {
                            socialMediaManager.markUserAsReadRules(userId: userId)
                            onConfirm()
                            dismissWithAnimation()
                        }) {
                            HStack(spacing: 10) {
                                Image(systemName: "checkmark.circle.fill")
                                    .font(.system(size: 18, weight: .semibold))
                                Text(language == "zh" ? "确认已读并同意" : "Confirm Read and Agree")
                                    .font(.system(size: 16, weight: .bold, design: .rounded))
                            }
                            .foregroundColor(.white)
                            .frame(maxWidth: .infinity)
                            .padding(.vertical, 16)
                            .background(
                                ZStack {
                                    LinearGradient(
                                        colors: [
                                            Color(red: 0.0, green: 0.8, blue: 1.0),
                                            Color(red: 0.2, green: 0.7, blue: 1.0),
                                            Color(red: 0.4, green: 0.6, blue: 1.0)
                                        ],
                                        startPoint: .topLeading,
                                        endPoint: .bottomTrailing
                                    )
                                    
                                    // 光泽效果
                                    LinearGradient(
                                        colors: [
                                            Color.white.opacity(0.3),
                                            Color.clear,
                                            Color.clear
                                        ],
                                        startPoint: .topLeading,
                                        endPoint: .bottomTrailing
                                    )
                                }
                            )
                            .cornerRadius(14)
                            .shadow(color: Color(red: 0.0, green: 0.8, blue: 1.0).opacity(0.4), radius: 12, x: 0, y: 6)
                        }
                        .scaleEffect(1.0)
                        .animation(.spring(response: 0.4, dampingFraction: 0.8), value: showConfirmButton)
                        .padding(.horizontal, 20)
                        .padding(.top, 16)
                        .padding(.bottom, 20)
                    }
                    .background(
                        LinearGradient(
                            colors: [
                                Color(red: 0.05, green: 0.05, blue: 0.15).opacity(0.95),
                                Color(red: 0.08, green: 0.08, blue: 0.20).opacity(0.98),
                                Color(red: 0.1, green: 0.1, blue: 0.25)
                            ],
                            startPoint: .top,
                            endPoint: .bottom
                        )
                    )
                    .transition(.asymmetric(
                        insertion: .move(edge: .bottom).combined(with: .opacity).combined(with: .scale(scale: 0.95)),
                        removal: .move(edge: .bottom).combined(with: .opacity)
                    ))
                }
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(
                ZStack {
                    // 主背景
                    RoundedRectangle(cornerRadius: 20)
                        .fill(
                            LinearGradient(
                                colors: [
                                    Color(red: 0.06, green: 0.06, blue: 0.18),
                                    Color(red: 0.08, green: 0.08, blue: 0.22),
                                    Color(red: 0.05, green: 0.05, blue: 0.20),
                                    Color(red: 0.1, green: 0.1, blue: 0.25)
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                    
                    // 边框光效
                    RoundedRectangle(cornerRadius: 20)
                        .stroke(
                            LinearGradient(
                                colors: [
                                    Color(red: 0.0, green: 0.8, blue: 1.0).opacity(0.6),
                                    Color.clear,
                                    Color(red: 0.4, green: 0.6, blue: 1.0).opacity(0.4),
                                    Color.clear
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            ),
                            lineWidth: 1.5
                        )
                    
                    // 内部光泽
                    RoundedRectangle(cornerRadius: 20)
                        .fill(
                            RadialGradient(
                                colors: [
                                    Color.white.opacity(0.08),
                                    Color.clear
                                ],
                                center: .topLeading,
                                startRadius: 0,
                                endRadius: 200
                            )
                        )
                }
                .shadow(color: .black.opacity(0.4), radius: 25, x: 0, y: 15)
                .shadow(color: Color(red: 0.0, green: 0.8, blue: 1.0).opacity(0.2), radius: 15, x: 0, y: 5)
            )
            .scaleEffect(animateContent ? 1.0 : 0.9)
            .opacity(animateContent ? 1.0 : 0.0)
            .animation(.spring(response: 0.6, dampingFraction: 0.8).delay(0.1), value: animateContent)
            .padding(.horizontal, 16)
            .padding(.vertical, 50)
        }
        .onAppear {
            withAnimation {
                animateBackground = true
                animateContent = true
            }
        }
    }
    
    private var rulesContent: some View {
        VStack(alignment: .leading, spacing: 18) {
            // 支持平台 - 优化设计
            modernRuleSection(
                icon: "📱",
                title: language == "zh" ? "支持平台" : "Supported Platforms",
                content: language == "zh" ? "Google Review / 小红书 / Instagram / Facebook / TikTok / Youtube" : "Google Review / Xiaohongshu / Instagram / Facebook / TikTok / Youtube",
                accentColor: Color(red: 0.0, green: 0.8, blue: 1.0)
            )
            
            // 积分奖励 - 优化设计
            modernCardSection(
                icon: "💰",
                title: language == "zh" ? "积分奖励" : "Points Rewards",
                accentColor: Color(red: 0.8, green: 0.4, blue: 1.0)
            ) {
                VStack(alignment: .leading, spacing: 14) {
                    modernSubsectionHeader(
                        title: language == "zh" ? "互动类型" : "Interaction Types",
                        color: Color(red: 0.8, green: 0.4, blue: 1.0)
                    )
                    
                    VStack(spacing: 8) {
                        modernPointsRow(icon: "👍", text: language == "zh" ? "点赞他人内容" : "Like others' content", points: "+2", color: Color.green)
                        modernPointsRow(icon: "🔄", text: language == "zh" ? "转发分享内容" : "Share content", points: "+2", color: Color.blue)
                        modernPointsRow(icon: "✨", text: language == "zh" ? "发布原创内容" : "Post original content", points: "+10", color: Color.orange)
                    }
                    
                    modernSubsectionHeader(
                        title: language == "zh" ? "积分限制" : "Points Limits",
                        color: Color(red: 0.8, green: 0.4, blue: 1.0)
                    )
                    
                    VStack(spacing: 8) {
                        modernLimitRow(icon: "📅", text: language == "zh" ? "每日上限" : "Daily limit", limit: "45")
                        modernLimitRow(icon: "📆", text: language == "zh" ? "每月上限" : "Monthly limit", limit: "800")
                    }
                }
            }
            
            // 参与流程 - 优化设计
            modernCardSection(
                icon: "📋",
                title: language == "zh" ? "参与流程" : "Participation Process",
                accentColor: Color(red: 0.2, green: 0.8, blue: 0.6)
            ) {
                VStack(spacing: 10) {
                    modernFlowStep(number: "1", text: language == "zh" ? "选择平台 - 从社交平台中选择" : "Select Platform - Choose from social platforms")
                    modernFlowStep(number: "2", text: language == "zh" ? "选择互动类型 - 点赞/转发/原创" : "Select Interaction Type - Like/Share/Original")
                    modernFlowStep(number: "3", text: language == "zh" ? "提交证据 - 上传截图或提供链接" : "Submit Evidence - Upload screenshot or provide link")
                    modernFlowStep(number: "4", text: language == "zh" ? "填写描述 - 简单描述您的互动内容（可选）" : "Fill Description - Briefly describe your interaction (optional)")
                    modernFlowStep(number: "5", text: language == "zh" ? "等待审核 - 管理员审核通过后积分生效" : "Wait for Review - Points take effect after admin approval")
                }
            }
            
            // 积分用途 - 优化设计
            modernCardSection(
                icon: "🎁",
                title: language == "zh" ? "积分用途" : "Points Usage",
                accentColor: Color(red: 1.0, green: 0.6, blue: 0.2)
            ) {
                VStack(alignment: .leading, spacing: 12) {
                    Text(language == "zh" ? "您所获得的积分可用于以下用途：" : "Your earned points can be used for:")
                        .font(.system(size: 13, weight: .medium))
                        .foregroundColor(.white.opacity(0.85))
                    
                    VStack(spacing: 8) {
                        modernUsageRow(icon: "🎟️", text: language == "zh" ? "兑换专属礼券与优惠" : "Redeem exclusive vouchers and discounts")
                        modernUsageRow(icon: "🥤", text: language == "zh" ? "不同会员等级可将积分按比例抵扣现金消费" : "Different membership levels can use points to offset cash consumption")
                        modernUsageRow(icon: "🚀", text: language == "zh" ? "会员等级晋升（Rookie → Vibe → Elite → Supreme）" : "Membership level promotion (Rookie → Vibe → Elite → Supreme)")
                    }
                }
            }
            
            // 重要提醒 - 优化设计
            modernWarningSection(
                icon: "⚠️",
                title: language == "zh" ? "重要提醒" : "Important Reminders"
            ) {
                VStack(spacing: 8) {
                    modernReminderRow(icon: "✅", text: language == "zh" ? "仅限真实有效的互动内容，恶意刷分将被系统自动识别并撤销积分" : "Only genuine interactions allowed, malicious point farming will be detected and points revoked")
                    modernReminderRow(icon: "🕐", text: language == "zh" ? "提交后预计24小时内完成审核，特殊情况可能延迟" : "Review expected within 24 hours, may be delayed in special circumstances")
                    modernReminderRow(icon: "📵", text: language == "zh" ? "禁止发布不当言论、虚假评论、非品牌相关内容" : "Prohibited: inappropriate content, fake reviews, non-brand related content")
                    modernReminderRow(icon: "🚫", text: language == "zh" ? "发现重复提交/虚假操作/冒用他人内容，将取消所有相关积分，并保留禁用账户的权利" : "Duplicate submissions/fake operations/impersonation will result in point cancellation and potential account suspension")
                    modernReminderRow(icon: "📲", text: language == "zh" ? "提交内容必须公开可见，否则将不予通过" : "Submitted content must be publicly visible, otherwise will not be approved")
                }
            }
            
            // 条款声明 - 优化设计
            modernCardSection(
                icon: "📜",
                title: language == "zh" ? "条款声明" : "Terms Declaration",
                accentColor: Color.gray
            ) {
                VStack(spacing: 8) {
                    modernTermsRow(text: language == "zh" ? "本活动最终解释权归本餐厅（Cu Mr Bull Pte. Ltd.) 所有。" : "Final interpretation rights belong to Cu Mr Bull Pte. Ltd.")
                    modernTermsRow(text: language == "zh" ? "本规则如有调整，将于 App 内提前公布，恕不另行通知。" : "Rule changes will be announced in the app in advance without separate notice.")
                    modernTermsRow(text: language == "zh" ? "积分不具备现金价值，亦不可转赠、交易或套现。" : "Points have no cash value and cannot be transferred, traded, or cashed out.")
                }
            }
            
            // 底部标识
            HStack {
                Spacer()
                Text("bottom")
                    .id("bottom")
                    .opacity(0)
                Spacer()
            }
        }
    }
    
    // MARK: - 优化的UI组件
    
    private func modernRuleSection(icon: String, title: String, content: String, accentColor: Color) -> some View {
        VStack(alignment: .leading, spacing: 10) {
            HStack(spacing: 8) {
                Text(icon)
                    .font(.system(size: 16))
                Text(title)
                    .font(.system(size: 16, weight: .bold, design: .rounded))
                    .foregroundColor(accentColor)
            }
            
            Text(content)
                .font(.system(size: 13, weight: .medium))
                .foregroundColor(.white.opacity(0.85))
                .lineLimit(nil)
        }
        .padding(16)
        .background(
            RoundedRectangle(cornerRadius: 12)
                .fill(
                    LinearGradient(
                        colors: [
                            Color.white.opacity(0.08),
                            Color.white.opacity(0.04)
                        ],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
                .overlay(
                    RoundedRectangle(cornerRadius: 12)
                        .stroke(accentColor.opacity(0.3), lineWidth: 1)
                )
        )
    }
    
    private func modernCardSection<Content: View>(icon: String, title: String, accentColor: Color, @ViewBuilder content: () -> Content) -> some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack(spacing: 8) {
                Text(icon)
                    .font(.system(size: 16))
                Text(title)
                    .font(.system(size: 16, weight: .bold, design: .rounded))
                    .foregroundColor(accentColor)
            }
            
            content()
        }
        .padding(16)
        .background(
            RoundedRectangle(cornerRadius: 12)
                .fill(
                    LinearGradient(
                        colors: [
                            Color.white.opacity(0.08),
                            Color.white.opacity(0.04)
                        ],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
                .overlay(
                    RoundedRectangle(cornerRadius: 12)
                        .stroke(accentColor.opacity(0.3), lineWidth: 1)
                )
        )
    }
    
    private func modernWarningSection<Content: View>(icon: String, title: String, @ViewBuilder content: () -> Content) -> some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack(spacing: 8) {
                Text(icon)
                    .font(.system(size: 16))
                Text(title)
                    .font(.system(size: 16, weight: .bold, design: .rounded))
                    .foregroundColor(Color.orange)
            }
            
            content()
        }
        .padding(16)
        .background(
            RoundedRectangle(cornerRadius: 12)
                .fill(
                    LinearGradient(
                        colors: [
                            Color.orange.opacity(0.15),
                            Color.orange.opacity(0.08)
                        ],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
                .overlay(
                    RoundedRectangle(cornerRadius: 12)
                        .stroke(Color.orange.opacity(0.4), lineWidth: 1)
                )
        )
    }
    
    private func modernSubsectionHeader(title: String, color: Color) -> some View {
        Text(title)
            .font(.system(size: 14, weight: .semibold, design: .rounded))
            .foregroundColor(color.opacity(0.9))
            .padding(.top, 4)
    }
    
    private func modernPointsRow(icon: String, text: String, points: String, color: Color) -> some View {
        HStack(spacing: 10) {
            Text(icon)
                .font(.system(size: 14))
            Text(text)
                .font(.system(size: 13, weight: .medium))
                .foregroundColor(.white.opacity(0.85))
            Spacer()
            Text(points)
                .font(.system(size: 13, weight: .bold, design: .rounded))
                .foregroundColor(color)
                .padding(.horizontal, 8)
                .padding(.vertical, 2)
                .background(
                    RoundedRectangle(cornerRadius: 6)
                        .fill(color.opacity(0.2))
                )
        }
    }
    
    private func modernLimitRow(icon: String, text: String, limit: String) -> some View {
        HStack(spacing: 10) {
            Text(icon)
                .font(.system(size: 14))
            Text(text)
                .font(.system(size: 13, weight: .medium))
                .foregroundColor(.white.opacity(0.85))
            Spacer()
            Text("\(limit) 积分")
                .font(.system(size: 13, weight: .bold, design: .rounded))
                .foregroundColor(Color(red: 0.8, green: 0.4, blue: 1.0))
        }
    }
    
    private func modernFlowStep(number: String, text: String) -> some View {
        HStack(spacing: 12) {
            Text(number)
                .font(.system(size: 12, weight: .bold, design: .rounded))
                .foregroundColor(.white)
                .frame(width: 22, height: 22)
                .background(
                    Circle()
                        .fill(
                            LinearGradient(
                                colors: [
                                    Color(red: 0.2, green: 0.8, blue: 0.6),
                                    Color(red: 0.1, green: 0.7, blue: 0.5)
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .shadow(color: Color(red: 0.2, green: 0.8, blue: 0.6).opacity(0.4), radius: 4, x: 0, y: 2)
                )
            Text(text)
                .font(.system(size: 13, weight: .medium))
                .foregroundColor(.white.opacity(0.85))
                .lineLimit(nil)
            Spacer()
        }
    }
    
    private func modernUsageRow(icon: String, text: String) -> some View {
        HStack(alignment: .top, spacing: 10) {
            Text(icon)
                .font(.system(size: 14))
            Text(text)
                .font(.system(size: 13, weight: .medium))
                .foregroundColor(.white.opacity(0.85))
                .lineLimit(nil)
            Spacer()
        }
    }
    
    private func modernReminderRow(icon: String, text: String) -> some View {
        HStack(alignment: .top, spacing: 10) {
            Text(icon)
                .font(.system(size: 14))
            Text(text)
                .font(.system(size: 13, weight: .medium))
                .foregroundColor(.white.opacity(0.9))
                .lineLimit(nil)
            Spacer()
        }
    }
    
    private func modernTermsRow(text: String) -> some View {
        HStack(alignment: .top, spacing: 10) {
            Text("•")
                .font(.system(size: 14, weight: .bold))
                .foregroundColor(.white.opacity(0.6))
            Text(text)
                .font(.system(size: 13, weight: .medium))
                .foregroundColor(.white.opacity(0.8))
                .lineLimit(nil)
            Spacer()
        }
    }
    
    private func checkScrollPosition(geometry: GeometryProxy) {
        let frame = geometry.frame(in: .global)
        if frame.maxY <= UIScreen.main.bounds.height {
            if !showConfirmButton {
                withAnimation(.spring(response: 0.6, dampingFraction: 0.8)) {
                    showConfirmButton = true
                }
            }
        }
    }
    
    private func dismissWithAnimation() {
        withAnimation(.easeInOut(duration: 0.3)) {
            animateContent = false
            animateBackground = false
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            presentationMode.wrappedValue.dismiss()
        }
    }
}

#Preview {
    SocialMediaRulesView(userId: "test-user", onConfirm: {})
        .environmentObject(DataManager.shared)
        .environmentObject(SocialMediaManager())
}